package tongwentongshu.com.app.model;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

import tongwentongshu.com.app.App;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.bean.RqcordBook;
import tongwentongshu.com.app.contract.ShareBookContract;
import tongwentongshu.com.app.presenter.SelectLocationPresenter;
import tongwentongshu.com.app.utils.ImageZip;
import tongwentongshu.com.app.utils.IntentUtils;
import tongwentongshu.com.app.utils.SystemUtils;

import static tongwentongshu.com.app.App.*;
import static tongwentongshu.com.app.presenter.SelectLocationPresenter.*;

/**
 * Created by XiongBin on 2017/6/27.
 */

public class ShareBookModel implements ShareBookContract.Model {
    private Activity act;
    private ShareBookContract.View sharebook;
    //以下是拍照相关
    public static final int request_camera = 100;
    public static final int req_camera = 10;
    public static final int req_gallery = 11;
    private File mFile;
    private int mWidth;//需要压缩的图片宽
    private int mHeight;//需要压缩的图片高



    public ShareBookModel(ShareBookContract.View sharebook) {
        this.sharebook = sharebook;
    }

    @Override
    public void getFileByPhotoAlbum(Activity act) {
        this.act = act;
        //拍照获取图片
        startCamera(Manifest.permission.CAMERA);
    }

    @Override
    public void getFileByPhotograph(Activity act) {
        this.act = act;
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        act.startActivityForResult(intent, req_gallery);
    }

    public void compressSize(int mWidth, int mHeight) {
        this.mWidth = mWidth;
        this.mHeight = mHeight;
    }

    private void startCamera(String permission) {
        if (ContextCompat.checkSelfPermission(act, permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(act, permission)) {
                Toast.makeText(act, "您已禁止该权限，需要重新开启。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(act, new String[]{permission},
                        request_camera);
            }
        } else {
            startCamera();
        }
    }

    private void startCamera() {
        //确定存储拍照得到的图片文件路径
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            mFile = new File(Environment.getExternalStorageDirectory(),
                    getName());
        } else {
            Toast.makeText(act, "请插入sd卡", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            mFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Intent intent = IntentUtils.startCamera(mFile);
        act.startActivityForResult(intent, req_camera);
    }

    @NonNull
    private String getName() {
        return System.currentTimeMillis() + ".jpg";
    }

    private void handleCamera(int grantResult) {
        if (grantResult == PackageManager.PERMISSION_GRANTED) {
            startCamera();
        } else {
            // Permission Denied
            Toast.makeText(act, "Permission Denied", Toast
                    .LENGTH_SHORT).show();
        }
    }

    /**
     * MIUI系统的相册选择
     *
     * @param data
     */
    private void setPhotoForMiuiSystem(Intent data) {
        Uri localUri = data.getData();
        String scheme = localUri.getScheme();
        String imagePath = "";
        if ("content".equals(scheme)) {
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = act.getContentResolver().query(localUri, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            imagePath = c.getString(columnIndex);
            c.close();
        } else if ("file".equals(scheme)) {//小米4选择云相册中的图片是根据此方法获得路径
            imagePath = localUri.getPath();
        }
        Bitmap bitmap = ImageZip.decodeSampledBitmapFromFile(imagePath, mWidth, mHeight);
        sharebook.setBookImage(bitmap, imagePath);
    }

    private void setPhotoForNormalSystem(Intent data) {
        String filePath = getRealPathFromURI(data.getData());
        Bitmap bitmap = ImageZip.decodeSampledBitmapFromFile(filePath, mWidth, mHeight);
        sharebook.setBookImage(bitmap, filePath);
    }

    /**
     * 解析Intent.getdata()得到的uri为String型的filePath
     *
     * @param contentUri
     * @return
     */
    public String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Audio.Media.DATA};
        Cursor cursor = act.managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == 0 ) {
        switch (resultCode) {
            case SelectLocationCode:
                Bundle locationBundle = data.getExtras();
                String poi_title = locationBundle.getString("poi_title");
                Log.e("tag", "poi_title=" + poi_title);
                sharebook.setLocation(poi_title);
                break;
            case CaptureCode:
                Bundle codeBundle = data.getExtras();
                RqcordBook rqcordBook = (RqcordBook) codeBundle.getSerializable("rqcordBook");
                sharebook.setCodeData(rqcordBook);
                break;
        }

//        }
        if (resultCode != act.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case req_camera:
                Bitmap bmp = ImageZip.decodeSampledBitmapFromFile(mFile.getAbsolutePath()
                        , mWidth, mHeight);
                sharebook.setBookImage(bmp, mFile.getAbsolutePath());
            /*    Intent intent = IntentUtils.cropPic(Uri.fromFile(mFile));
                startActivityForResult(intent,req_crop);*/
                break;
            case req_gallery:
                if (SystemUtils.isMIUI()) {
                    setPhotoForMiuiSystem(data);
                } else {
                    setPhotoForNormalSystem(data);
                }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case req_camera:
                handleCamera(grantResults[0]);
                break;
        }
    }
}
